<template>
  <div class="main-layout">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <div class="logo">
          <el-icon class="logo-icon"><Grid /></el-icon>
          <span class="logo-text">布匹销售系统</span>
        </div>
      </div>
      <div class="header-right">
        <el-space>
          <el-badge :value="3" class="notification-badge">
            <el-button :icon="Bell" circle />
          </el-badge>
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-avatar :size="32" :src="userAvatar" />
              <span class="username">{{ username }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><User /></el-icon>
                  个人中心
                </el-dropdown-item>
                <el-dropdown-item command="settings">
                  <el-icon><Setting /></el-icon>
                  系统设置
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-space>
      </div>
    </el-header>

    <el-container class="main-container">
      <!-- 侧边导航栏 -->
      <el-aside :width="isCollapse ? '64px' : '180px'" class="sidebar">
        <div class="sidebar-header">
          <el-button
            :icon="isCollapse ? Expand : Fold"
            @click="toggleCollapse"
            text
            class="collapse-btn"
          />
        </div>
        <el-menu
          :default-active="activeMenu"
          :collapse="isCollapse"
          :unique-opened="true"
          router
          class="sidebar-menu"
        >
          <template v-for="menu in menuConfig" :key="menu.index">
            <!-- 单级菜单 -->
            <el-menu-item v-if="!menu.children" :index="menu.index">
              <el-icon><component :is="menu.icon" /></el-icon>
              <template #title>{{ menu.title }}</template>
            </el-menu-item>

            <!-- 多级菜单 -->
            <el-sub-menu v-else :index="menu.index">
              <template #title>
                <el-icon><component :is="menu.icon" /></el-icon>
                <span>{{ menu.title }}</span>
              </template>
              <el-menu-item v-for="child in menu.children" :key="child.index" :index="child.index">
                <el-icon><component :is="child.icon" /></el-icon>
                <template #title>{{ child.title }}</template>
              </el-menu-item>
            </el-sub-menu>
          </template>
        </el-menu>
      </el-aside>

      <!-- 主内容区域 -->
      <el-main class="main-content">
        <!-- 面包屑导航 -->
        <div class="breadcrumb-container">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item
              v-for="item in breadcrumbList"
              :key="item.path"
              :to="item.path ? { path: item.path } : undefined"
            >
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <!-- 页面内容 -->
        <div class="page-content">
          <router-view v-slot="{ Component }">
            <transition name="fade-transform" mode="out-in">
              <component :is="Component" />
            </transition>
          </router-view>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  Grid,
  Bell,
  ArrowDown,
  User,
  Setting,
  SwitchButton,
  Expand,
  Fold,
  Odometer,
  List,
  TrendCharts,
  Document,
  DataAnalysis,
  PieChart,
  UserFilled,
  Goods,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 侧边栏折叠状态
const isCollapse = ref(false)

// 用户信息
const username = ref(localStorage.getItem('username') || '管理员')
const userAvatar = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png')

// 当前激活的菜单
const activeMenu = computed(() => route.path)

// 面包屑导航
const breadcrumbList = ref<Array<{ title: string; path?: string }>>([])

// 菜单配置接口
interface MenuConfig {
  index: string
  title: string
  icon: string
  children?: MenuConfig[]
}

/**
 * 根据路由配置动态生成菜单配置
 * @returns {MenuConfig[]} 菜单配置数组
 */
const generateMenuConfig = (): MenuConfig[] => {
  const routes = router.getRoutes()
  const menuGroups = new Map<string, MenuConfig>()
  const singleMenus: MenuConfig[] = []

  // 过滤出需要显示在菜单中的路由
  const menuRoutes = routes
    .filter((route) => {
      const meta = route.meta as any
      return meta?.showInMenu && route.path !== '/'
    })
    .sort((a, b) => {
      const aOrder = (a.meta as any)?.menuOrder || 999
      const bOrder = (b.meta as any)?.menuOrder || 999
      return aOrder - bOrder
    })

  menuRoutes.forEach((route) => {
    const meta = route.meta as any
    const menuItem: MenuConfig = {
      index: route.path,
      title: meta.title,
      icon: meta.icon,
    }

    if (meta.menuGroup) {
      // 分组菜单
      if (!menuGroups.has(meta.menuGroup)) {
        menuGroups.set(meta.menuGroup, {
          index: meta.menuGroup,
          title: meta.menuGroupTitle,
          icon: meta.menuGroupIcon,
          children: [],
        })
      }
      menuGroups.get(meta.menuGroup)!.children!.push(menuItem)
    } else {
      // 单级菜单
      singleMenus.push(menuItem)
    }
  })

  // 合并单级菜单和分组菜单
  const result: MenuConfig[] = []

  menuRoutes.forEach((route) => {
    const meta = route.meta as any
    const menuOrder = meta.menuOrder

    if (!meta.menuGroup) {
      // 添加单级菜单
      const menuItem = singleMenus.find((item) => item.index === route.path)
      if (menuItem && !result.some((item) => item.index === menuItem.index)) {
        result.push(menuItem)
      }
    } else {
      // 添加分组菜单（只添加一次）
      const groupMenu = menuGroups.get(meta.menuGroup)
      if (groupMenu && !result.some((item) => item.index === groupMenu.index)) {
        result.push(groupMenu)
      }
    }
  })

  return result
}

// 动态生成菜单配置
const menuConfig = ref<MenuConfig[]>(generateMenuConfig())

// 路由映射表（用于面包屑导航）
const routeMap: Record<string, string> = {
  '/dashboard': '数据概览',
  '/customer': '客户管理',
  '/customer/list': '客户列表',
  '/customer/profile': '客户画像分析',
  '/order': '订单管理',
  '/order/list': '订单列表',
  '/order/statistics': '订单统计',
  '/analytics': '数据分析',
  '/analytics/sales': '销售分析',
  '/analytics/customer': '客户分析',
  '/analytics/product': '产品分析',
  '/product/list': '产品列表',
  '/users/list': '用户管理',
  '/settings': '系统设置',
}

// 切换侧边栏折叠状态
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

/**
 * 处理用户下拉菜单命令
 * @param {string} command - 菜单命令
 */
const handleCommand = (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      handleLogout()
      break
  }
}

/**
 * 处理退出登录逻辑
 */
const handleLogout = () => {
  // 清除登录状态
  localStorage.removeItem('isLoggedIn')
  localStorage.removeItem('username')
  localStorage.removeItem('loginTime')

  ElMessage.success('退出登录成功')

  // 跳转到登录页
  router.push('/login')
}

// 更新面包屑导航
const updateBreadcrumb = () => {
  const pathArray = route.path.split('/').filter((item) => item)
  const breadcrumbs: Array<{ title: string; path?: string }> = []

  let currentPath = ''
  pathArray.forEach((path, index) => {
    currentPath += `/${path}`
    const title = routeMap[currentPath]
    if (title && index < pathArray.length - 1) {
      breadcrumbs.push({ title, path: currentPath })
    } else if (title) {
      breadcrumbs.push({ title })
    }
  })

  breadcrumbList.value = breadcrumbs
}

// 监听路由变化
watch(
  () => route.path,
  () => {
    updateBreadcrumb()
  },
  { immediate: true },
)
</script>

<style scoped>
.main-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #1890ff;
}

.logo-icon {
  font-size: 24px;
  margin-right: 8px;
}

.logo-text {
  color: #2c3e50;
}

.header-right {
  display: flex;
  align-items: center;
}

.notification-badge {
  margin-right: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f5f5;
}

.username {
  margin: 0 8px;
  font-size: 14px;
  color: #606266;
}

.main-container {
  flex: 1;
  height: calc(100vh - 60px);
}

.sidebar {
  background: #fff;
  border-right: 1px solid #e4e7ed;
  transition: width 0.3s;
  overflow: hidden;
}

.sidebar-header {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #e4e7ed;
}

.collapse-btn {
  color: #606266;
}

.sidebar-menu {
  border: none;
  height: calc(100% - 48px);
}

.sidebar-menu .el-menu-item,
.sidebar-menu .el-sub-menu__title {
  height: 48px;
  line-height: 48px;
}

.main-content {
  background: #f5f5f5;
  padding: 0;
  overflow: auto;
}

.breadcrumb-container {
  background: #fff;
  padding: 12px 20px;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 16px;
}

.page-content {
  padding: 0 20px 20px;
  min-height: calc(100vh - 60px - 48px - 16px);
}

/* 页面切换动画 */
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    padding: 0 16px;
  }

  .logo-text {
    display: none;
  }

  .username {
    display: none;
  }

  .sidebar {
    position: fixed;
    z-index: 1000;
    height: 100%;
  }

  .main-content {
    margin-left: 0;
  }

  .page-content {
    padding: 0 16px 16px;
  }
}
</style>
